<template>
  <div v-if="!disabled" ref="elementRef" id="draggable-only-id" :style="{ transform: `translate(${x}px, ${y}px)` }">
    <div class="body">
      <slot />
    </div>
  </div>
</template>

<script>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue';
import Draggable from 'draggable';

export default {
  name: 'Draggable',
  props: {
    x: { type: Number, default: 0 },
    y: { type: Number, default: 0 },
    disabled: { type: Boolean, default: false },
    datalist: { type: Object, default: () => ({}) }
  },
  emits: ['update:x', 'update:y', 'update:disabled', 'update:datalist'],
  setup(props, { emit }) {
    const draggable = ref(null);
    const elementRef = ref(null);

    // 创建拖拽实例
    const createDraggable = () => {
      if (elementRef.value) {
        draggable.value = new Draggable(elementRef.value, {
          onDrag: (event) => {
            emit('update:x', props.x + event.deltaX);
            emit('update:y', props.y + event.deltaY);
          },
        });
      }
    };

    // 销毁拖拽实例
    const destroyDraggable = () => {
      if (draggable.value) {
        draggable.value.destroy();
        draggable.value = null;
      }
    };

    // 监听 disabled 变化
    watch(
      () => props.disabled,
      (newVal) => {
        if (!newVal) {
          destroyDraggable();
        } else {
          // 等待 DOM 更新后创建实例
          setTimeout(createDraggable, 100);
        }
      }
    );

    // 组件挂载时创建实例
    onMounted(() => {
      if (props.disabled) {
        createDraggable();
      }
    });

    // 组件销毁前清理实例
    onBeforeUnmount(() => {
      destroyDraggable();
    });

    const close = () => {
      emit('update:disabled', false);
      emit('update:datalist', {});
    };

    return {
      draggable,
      elementRef,
      close
    };
  },
};
</script>
<style scoped lang="less">
#draggable-only-id {
  width: 300px;
  background-color: #fff;
  border-radius: 5px;
  height: auto !important;

  .self_drabbable_top {
    cursor: move;
    width: 100%;
    height: 4.2vh;
    background: #1384EA;
    border-bottom: 1px solid #ebebeb;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .self_drabbable_top_text {
      font-size: 18px;
      color: #fff;
      font-weight: 600;
      margin-left: 0.3vw;
    }

    .self_drabbable_top_btn {
      width: 16px;
      height: 16px;
      background: #fff;
      border-radius: 50%;
      margin-right: 1vw;
    }
  }

  &>.header {
    padding: 10px;
    color: #fff;
    line-height: 1.5;
    font-weight: bolder;
    cursor: move;
  }

  &>.body {
    max-height: 400px;
    overflow-y: auto;
    padding: 0 10px;
  }
}
</style>